#!/bin/sh

submiturl=localhost:9980/org.honeynet.hbbackend.submithttp/submit
#verbosecurl=-v
md5cmd="md5 -q"
sha512cmd="{ openssl sha512 | cut -d' ' -f2 ;}"

ipsfile=$1
bindir=$2

ips=$(sed -E '/^[0-9.]{7,}$/!d' < $ipsfile | wc -l)
((ips--))
source_ip=$(sed -E '/^[0-9.]{7,}$/!d' < $ipsfile | head -n $(( RANDOM % $ips + 1 )) | tail -n1)
target_ip=""
while [ -z "$target_ip" ] || [ "$target_ip" == "$source_ip" ] ; do
    target_ip=$(sed -E '/^[0-9.]{7,}$/!d' < $ipsfile | head -n $(( RANDOM % $ips + 1 )) | tail -n1)
done

files=$(ls $bindir | sed '/\.bin$/!d' | wc -l)
((files--))
f=$(ls $bindir | sed '/\.bin$/!d' | head -n $(( RANDOM % $files + 1 )) | tail -n1)

md5=$(eval $md5cmd < $bindir/$f)
sha512=$(eval $sha512cmd < $bindir/$f)


function phase1() {
curl $verbosecurl -u honeypot:secretpass -F source_host=$source_ip -F source_port=$(( RANDOM % 60000 + 2000 )) -F target_host=$target_ip -F target_port=$(( RANDOM % 1020 + 1 )) -F url=test -F trigger=test -F filename=$f -F filetype=test -F md5=$md5 -F sha512=$sha512  $submiturl
}

function phase2() {
curl $verbosecurl -u honeypot:secretpass -F source_host=$source_ip -F source_port=$(( RANDOM % 60000 + 2000 )) -F target_host=$target_ip -F target_port=$(( RANDOM % 1020 + 1 )) -F url=test -F trigger=test -F filename=$f -F filetype=test -F md5=$md5 -F sha512=$sha512 -F "data=@$bindir/$f" $submiturl
}

echo
echo "submitting $bindir/$f"
echo
echo "md5=$md5"
echo "source_host=$source_ip target_host=$target_ip"
echo
echo

reply="$(phase1)"

case "$reply" in
    S_FILEREQUEST) echo ; echo $reply ; echo ; reply="$(phase2)" ;;
    S_FILEKNOWN) echo ; echo $reply ; echo ; exit ;;
    *) echo ; echo 'unexpected reply=' ; echo ; echo "$reply" ; exit 1 ;;
esac

case "$reply" in
    S_FILEOK) echo ; echo $reply ; echo ; echo ; exit 0 ;;
    *) echo ; echo 'unexpected reply=' ; echo ; echo "$reply" ; echo ; echo ; exit 1 ;;
esac

